package cn.tedu.charging.order.config;

import net.sf.jsqlparser.statement.select.Top;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * rabbit-mq 配置类
 * 连接信息 用户名 密码...
 * QUEUE EXCHANGE
 */
@Configuration
public class RabbitMQConfig {

    //可以通过配置文件来配置
    public static final String ORDER_QUEUE = "order.queue";

    /**
     * 订单正常的Exchange
     */
    public static final String ORDER_EXCHANGE = "order.exchange";

    /**
     * 订单正常的Exchange
     */
    public static final String ORDER_ROUTING_KEY = "order";

    /**
     * 订单死信的Exchange
     */
    public static final String ORDER_DEAD_LETTER_EXCHANGE = "order.dead.letter.exchange";

    /**
     * 死信Exchange 和 死信队列绑定的routing-key
     */
    public static final String ROUTING_DEAD_LETTER_KEY = "order.dead.letter.routing.key";


    /**
     * 订单死信的Queue
     */
    public static final String ORDER_DEAD_LETTER_QUEUE = "order.dead.letter.queue";

    /**
     * 定义订单队列
     * @return
     */
    @Bean
    public Queue orderQueue() {
        //name 队列名称
        //durable 是否持久化 true重启后数据不会丢失
        //exclusive 是否独占队列
        //autoDelete 是否自动删除 true 临时队列  长时间不用就干掉 (队列里最后一条消息被消费了,队列会被自动删除)
        Map<String, Object> args = new HashMap<String, Object>();
        //死信的exchange
        args.put("x-dead-letter-exchange", ORDER_DEAD_LETTER_EXCHANGE);
        //死信的routing-key
        args.put("x-dead-letter-routing-key", ROUTING_DEAD_LETTER_KEY);
        //模拟充电需要2分钟 2 * 60 * 1000
        Integer ttl = 5 * 60 * 1000;
        //指定存活时间
        args.put("x-message-ttl", ttl);
        //惰性队列,在消息很多的时候,存到磁盘里,避免消息积压,占内存
        args.put("x-queue-mode","lazy");
        Boolean durable = true;//消息是不能丢失的
        return new Queue(ORDER_QUEUE,durable,true,false,args);
    }

    /**
     * 定义订单Exchange 交换机
     * @return
     */
    @Bean
    public DirectExchange orderTopicExchange() {
        return new DirectExchange(ORDER_EXCHANGE);
    }

    /**
     * 把订单队列绑定到订单交换机上
     * @return
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder
                .bind(orderQueue())
                .to(orderTopicExchange()).with(ORDER_ROUTING_KEY);
    }

    /**
     * 定义死信Exchange
     * @return
     */
    @Bean
    public TopicExchange deadLetterExchange(){
        return new TopicExchange(ORDER_DEAD_LETTER_EXCHANGE,true,false);
    }

    /**
     * 定义死信Queue
     * @return
     */
    @Bean
    public Queue deadLetterQueue(){
        return new Queue(ORDER_DEAD_LETTER_QUEUE,true,false,false);
    }

    /**
     * 将死信队列和死信的交换机进行绑定
     * @return
     */
    @Bean
    public Binding deadLetterBinding(){
        return BindingBuilder
                .bind(deadLetterQueue())
                .to(deadLetterExchange()).with(ROUTING_DEAD_LETTER_KEY);
    }






}
